﻿using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Xml.Linq;
//
using PerceptiveMCAPI.Types.Internal;
//
namespace PerceptiveMCAPI.Types
{
	public class campaignEmailStatsAIMOutput : Api_BaseOutput
	{
		public campaignEmailStatsAIMResults result { get; set; }
		public campaignEmailStatsAIMParms inputParms { get; private set; }
		// --------------------------------------------------------
		public campaignEmailStatsAIMOutput( campaignEmailStatsAIMInput input )
			: base( input )
		{
			inputParms = input.parms;
			result = new campaignEmailStatsAIMResults();
		}
		// --------------------------------------------------- tostring
		public override string ToString()
		{
			return string.Format( "Email Stats Items: {0}", this.result.data.Count );
		}

		#region ================================================================== format setup

		// ---- serial
		internal void Format( string api_Request, string api_Response )
		{
			this.api_Request = api_Request;
			this.api_Response = api_Response;
			// ----------------------------------
			if ( this.api_OutputType == EnumValues.OutputType.JSON )
				outputJSON();
			else if ( this.api_OutputType == EnumValues.OutputType.XML )
				outputXML();
		}

		// ---- xmlrpc
		internal void Format( x_campaignEmailStatsAIM rpcResult )
		{
			this.api_Request = EnumValues.NotSupplied;
			this.api_Response = EnumValues.NotSupplied;
			// ------------------------
			this.result = FormatResults( rpcResult );
		}

		#endregion

		#region ================================================================= Output

		// --------------------------------------------
		private void outputXML()
		{
			XElement xml = XElement.Parse( this.api_Response );
			// error check
			Api_Error error = apiSerial.GetXmlOutputError( xml );
			if ( error != null )
			{
				this.api_ErrorMessages.Add( error );
				return;
			}
			// -------------------------------------------- get values
			DateTime dt; int it;
			try
			{
				int.TryParse( xml.Element( "success" ).Value, out it );
				result.success = it;
				int.TryParse( xml.Element( "error" ).Value, out it );
				result.error = it;
				//
				IEnumerable<XElement> aim = xml.Element( "data" ).Elements( "struct" );
				foreach ( XElement entry in aim )
				{
					campaignEmailStatsAIMResults.EmailActivity email_act = new campaignEmailStatsAIMResults.EmailActivity();
					email_act.email_address = entry.Element( "email_address" ).Value;
					if ( entry.Element( "activity" ).HasElements )
					{
						IEnumerable<XElement> activities = entry.Element( "activity" ).Elements( "struct" );
						foreach ( XElement activity in activities )
						{
							var item = new campaignEmailStatsAIMResults.EmailActivity.Activity();
							//
							item.action = activity.Element( "action" ).Value;
							DateTime.TryParse( activity.Element( "timestamp" ).Value, out dt );
							item.timestamp = dt;
							item.url = activity.Element( "url" ).Value;
							item.ip = activity.Element( "ip" ).Value;
							//
							email_act.activity.Add( item );
						}
					}
					this.result.data.Add( email_act );
				}
			}
			catch ( Exception ex )
			{
				this.api_ErrorMessages.Add( apiException.FormatError( ex ) );
			}
		}

		// ---------------------------------------------------------- outputJSON
		private void outputJSON()
		{
			JavaScriptSerializer jss = new JavaScriptSerializer();

			try
			{
				if ( this.api_Response.Contains( EnumValues.JSONErrorString ) )
				{
					Api_Error err = jss.Deserialize<Api_Error>( this.api_Response );
					this.api_ErrorMessages.Add( err );
				}
				else
				{
					x_campaignEmailStatsAIM jsonResult = jss.Deserialize<x_campaignEmailStatsAIM>( this.api_Response );
					this.result = FormatResults( jsonResult );
				}
			}
			catch ( Exception ex )
			{
				this.api_ErrorMessages.Add( apiException.FormatError( ex ) );
			}
		}

		// ---------------------------------------------------------- FormatResults
		private campaignEmailStatsAIMResults FormatResults( x_campaignEmailStatsAIM x_results )
		{
			campaignEmailStatsAIMResults results = new campaignEmailStatsAIMResults();
			//
			DateTime dt;
			results.success = x_results.success;
			results.error = x_results.error;
			if ( x_results.data == null || x_results.data.Length < 1 ) return results;
			//
			foreach ( var entry in x_results.data )
			{
				campaignEmailStatsAIMResults.EmailActivity email_activity = new campaignEmailStatsAIMResults.EmailActivity();
				email_activity.email_address = entry.email_address;
				foreach ( var x_act in entry.activity )
				{
					var item = new campaignEmailStatsAIMResults.EmailActivity.Activity();
					item.action = x_act.action ?? "";
					DateTime.TryParse( x_act.timestamp, out dt );
					item.timestamp = dt;
					item.ip = x_act.ip ?? "";
					item.url = x_act.url ?? "";
					email_activity.activity.Add( item );
				}
				//
				results.data.Add( email_activity );
			}

			return results;
		}

		#endregion
	}
}
